﻿using CanDoo.Core.Logging;
using CanDoo.Oil.WebApi.Api.Results;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http.Filters;
using System.Web.Http.ModelBinding;
using Autofac.Integration.Owin;
using Autofac;
using CanDoo.Data;
using CanDoo.Extensions;
using System.Threading;
using System.Threading.Tasks;
using CanDoo.Core.Security;
using System.ComponentModel;
using System.Diagnostics;

namespace CanDoo.Oil.WebApi.Areas.Api.Filters
{
    public class TinderApiExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            var result = new ApiResult<Exception>();
            result.ResultType = ApiResultType.error;
            result.Message = context.Exception.Message;
            result.InnerMessage = context.Exception.Message;
            result.Data = context.Exception;

            context.Response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(JsonConvert.SerializeObject(result), Encoding.GetEncoding("UTF-8"), "application/json")
            };

            IOperateLoger OperateLoger = context.Request.GetOwinContext().GetAutofacLifetimeScope().Resolve<IOperateLoger>();
            IPermissionManager PermissionManager = context.Request.GetOwinContext().GetAutofacLifetimeScope().Resolve<IPermissionManager>();

            var ActionName = context.ActionContext.ActionDescriptor.ActionName;
            var ActionDesc = context.ActionContext.ActionDescriptor.GetCustomAttributes<DescriptionAttribute>(false)?.FirstOrDefault()?.Description ?? ActionName;
            var ControllerName = context.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            var ControllerDesc = context.ActionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<DescriptionAttribute>(false)?.FirstOrDefault()?.Description ?? ControllerName;

            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(ActionName, ControllerName, ActionDesc, ControllerDesc);

            OperateLoger.InputMessage = context.Request.Content.ToString();
            OperateLoger.OutputMessage = context.Exception.Message;

            OperateLoger.OperationResult = new OperationResult(OperationResultType.Error, result.Message, null, context.Exception.FormatMessage());
            OperateLoger.SaveLog();
        }

        public override async Task OnExceptionAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
        {
            var context = actionExecutedContext;

            var result = new ApiResult<string>();
            result.ResultType = ApiResultType.error;
            result.Message = context.Exception.Message;
            result.InnerMessage = context.Exception.Message;
            result.Data = context.Exception.FormatMessage();

            context.Response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(JsonConvert.SerializeObject(result), Encoding.GetEncoding("UTF-8"), "application/json")
            };

            IOperateLoger OperateLoger = context.Request.GetOwinContext().GetAutofacLifetimeScope().Resolve<IOperateLoger>();
            IPermissionManager PermissionManager = context.Request.GetOwinContext().GetAutofacLifetimeScope().Resolve<IPermissionManager>();

            var ActionName = context.ActionContext.ActionDescriptor.ActionName;
            var ActionDesc = context.ActionContext.ActionDescriptor.GetCustomAttributes<DescriptionAttribute>(false)?.FirstOrDefault()?.Description ?? ActionName;
            var ControllerName = context.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            var ControllerDesc = context.ActionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<DescriptionAttribute>(false)?.FirstOrDefault()?.Description ?? ControllerName;

            OperateLoger.FunctionInfo = PermissionManager.GetFunctionInfo(ActionName, ControllerName, ActionDesc, ControllerDesc);

            OperateLoger.InputMessage = context.Request.Content.ToString();
            OperateLoger.OutputMessage = context.Exception.Message;

            OperateLoger.OperationResult = new OperationResult(OperationResultType.Error, result.Message,null, context.Exception.FormatMessage());
            await OperateLoger.SaveLogAsync();
            //await base.OnExceptionAsync(actionExecutedContext, cancellationToken);
            return;
        }
    }
}